/*
 * @Author: Charsen
 * @Date: 2025-07-25 15:25
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 10:24:38
 * @Description:
 */
import { api } from '#/api'
/**
 * 从对象数据中取出 key 和 value 组成新的 { label: STRING, value: STRING, children: CHILDREN }
 * @param {object} data
 * @param {string} id_field
 * @param {string} name_field
 * @param {string} count_field
 * @param deep
 * @returns {object}
 */
export function formatLabelValue<T>(
  data: object | T,
  id_field: string,
  name_field: string,
  count_field: string,
  deep = 0
): unknown {
  const res = []
  deep++
  if (deep === 1) {
    res.push({ label: '全部', value: '', count: 0 })
  }

  for (const i in data) {
    const one = {
      label: data[i][name_field],
      value: data[i][id_field],
      count: count_field ? data[i][count_field] : 0,
    }

    // eslint-disable-next-line no-prototype-builtins
    if (data[i].hasOwnProperty('children') && data[i].children.length > 0) {
      one.children = formatLabelValue(data[i].children, id_field, name_field, count_field, deep)
    }
    res.push(one)
  }
  return res
}

export function joinBy(data: any, field: string, separator = ', '): string {
  const res = []
  for (const i in data) {
    res.push(data[i][field])
  }
  return res.join(separator)
}

/**
 * 打开新标签页
 * @param href 链接
 */
export function openNew(href: string, type = '_blank') {
  let newWin = window.open('about:blank', type)
  if (newWin) {
    newWin.location.href = href
  }
  newWin = null
}

/**
 * 获取当前时间字符串
 * @returns {string}
 */
export function getTimeStr(): string {
  const today = new Date()
  return `${today.getFullYear()}-${
    today.getMonth() + 1
  }-${today.getDate()}-${today.getHours()}-${today.getMinutes()}-${today.getSeconds()}`
}

// URL 构建辅助函数
export function getUrl(
  entity?: string,
  customUrl?: ((id: number | string | string[] | undefined) => string) | string,
  action?: string,
  id?: number | string | string[]
): string {
  if (customUrl) {
    return typeof customUrl === 'function' ? customUrl(id) : customUrl
  }

  // 如果有 entity 且存在于 api 配置中，使用默认 URL
  if (entity && api[entity] && action) {
    return typeof api[entity][action] === 'function' ? api[entity][action](id) : api[entity][action]
  }

  // 如果都没有，抛出错误
  throw new Error(`无法构建 URL：请提供自定义 URL 或确保 entity "${entity}" 存在于 api 配置中`)
}

// 获取ID数组的工具函数
export function getIds(data: any[]): string[] {
  return data.map((item: any) => item.id)
}
